import { useState } from 'react';

/**
 * @useSourcePackage 寻源包的hooks
 * @param form
 * @param setLoading 设置全局loading
 * @returns
 */
export const useSourcePackage = ({ form, setLoading }: { form: any; setLoading: (state: boolean) => void }) => {
  // 寻源包的的内容
  const [sourcePackage, setSourcePackage] = useState([
    {
      id: '1',
      key: 'source-one',
      label: '寻源一',
      formInfo: {},
    },
    {
      id: '2',
      key: 'source-two',
      label: '寻源二',
      formInfo: {},
    },
  ]);

  // 寻源包的tabs的key值
  const [sourceTabsKey, setSourceTabsKey] = useState<string | undefined>(sourcePackage[0].key);

  /**
   * @description sourceChangeTabs 切换寻源包
   * @param activeKey 当前激活寻源包的tabs的key值
   */
  const sourceChangeTabs = (activeKey: string) => {
    // 暂时模拟loading
    setLoading(true);
    setTimeout(() => {
      setSourceTabsKey(activeKey);
      setLoading(false);
    }, 1000);

    // 切换寻源包的时，更新对应表单数据
    const tempSourcePackage = sourcePackage.map((item) => {
      const tempItem = {
        ...item,
        formInfo: item.key === sourceTabsKey ? form?.getFieldsValue() : item.formInfo,
      };

      // 当前激活activeKey与寻源包key对应，并判断有内容时更新表单内容
      item.key === activeKey ? (Object.keys(tempItem.formInfo).length ? form?.setFieldsValue(tempItem.formInfo) : form?.resetFields()) : null;
      return tempItem;
    });
    setSourcePackage(tempSourcePackage);
  };

  return {
    sourcePackage,
    setSourcePackage,
    sourceTabsKey,
    sourceChangeTabs,
  };
};
